import router from '@/router'
import { asyncRoutes } from '@/router/index'
import store from '@/store'
import NProgress from 'nprogress' // 引入一份进度条插件
import 'nprogress/nprogress.css' // 引入进度条样式

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const whiteList = ['/login', '/404']
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      const userInfo = store.state.user.userInfo
      if (Object.keys(userInfo).length <= 0) {
        const res = await store.dispatch('user/getUserInfo')
        // await store.dispatch('user/getUserInfo')
        console.log(res)
        //  这里需要进行权限判定
        // 1.获取用户对应的权限标识
        // 2.获取所有的动态路由
        // 3.拿动态路由和权限标识 进行筛选, 筛选出对应可以跳转的路由
        // 4.拿筛选之后的路由 添加到 路由对象中
        console.log(res.roles.menus)
        console.log(asyncRoutes)
        router.addRoutes(asyncRoutes)
        // todo 要保证addRoutrers确认添加成功之后，在进行跳转
        next({
          ...to,
          replace: true
        })
        return
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
